package com.xinruke.hostels.systemmanage.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xinruke.hostels.cache.extract.extractor.DictInfoCacheExtractor;
import com.xinruke.hostels.common.cache.ManageUserCache;
import com.xinruke.hostels.common.cache.vo.LoginManageResultVO;
import com.xinruke.hostels.common.constants.SysDicConstant;
import com.xinruke.hostels.common.mybatis.MyExample;
import com.xinruke.hostels.common.po.YwFangjianleixing;
import com.xinruke.hostels.common.util.RandomUtil;
import com.xinruke.hostels.common.vo.ResultVO;
import com.xinruke.hostels.common.vo.query.EConditionOperator;
import com.xinruke.hostels.common.vo.query.QueryConditions;
import com.xinruke.hostels.common.vo.query.RowsDataVO;
import com.xinruke.hostels.system.manage.interfaces.dto.*;
import com.xinruke.hostels.systemmanage.mapper.YwFangjianleixingMapper;
import com.xinruke.hostels.systemmanage.mapper.YwFangtairiqijiluMapper;
import com.xinruke.hostels.systemmanage.service.RoomService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author GuoZheng
 * @ClassName RoomTypeServiceImpl
 * @date：2019/6/23
 * @version: V1.0.0
 * @description：
 */
@Service
public class RoomTypeService {
    @Resource
    private YwFangjianleixingMapper ywFangjianleixingMapper;

    @Resource
    private RoomService roomService;

    @Autowired
    private ManageUserCache manageUserCache;

    @Resource
    private DictInfoCacheExtractor dictInfoCacheExtractor;

    @Resource
    YwFangtairiqijiluMapper fangtairiqijiluMapper;


    /**
     * 预订系统查询房型列表
     *
     * @param params
     * @return
     */
    public ResultVO<RowsDataVO<ReservationRoomTypeQueryResultDTO>> getReservationRoomType(ReservationRoomTypeQueryDTO params) {

        String order = params.getOrderFields().stream().filter(o -> !StringUtils.isEmpty(o.getOrderField())).map(o -> o.getOrderField() + (o.getOrderDesc() ? " DESC" : " ASC")).reduce((s1, s2) -> s1 + "," + s2).orElse("");
        Page page = PageHelper.startPage(params.getPageNo(), params.getPageSize(), order);
        //根据查询条件查询RoomList
        List<ReservationRoomTypeQueryResultDTO> resultDTOList = ywFangjianleixingMapper.selectPersonalRoomType(params);
        resultDTOList.forEach(dto -> {
            dto.setShangwangfangshiMingcheng(dictInfoCacheExtractor.getDictValue(SysDicConstant.SHANGWANGFANGSHI, dto.getShangwangfangshi()));
            dto.setZaocanleixingMingcheng(dictInfoCacheExtractor.getDictValue(SysDicConstant.ZAOCANLEIXING, dto.getZaocanleixing() ));
            dto.setTypeName(dictInfoCacheExtractor.getDictValue(SysDicConstant.FANGJIANLEIXING, dto.getType()));

        });

        RowsDataVO<ReservationRoomTypeQueryResultDTO> dataVO = new RowsDataVO();
        dataVO.setPageNo(page.getPageNum());
        dataVO.setTotalRecords(page.getTotal());
        dataVO.setTotalPages(page.getPages());
        dataVO.setRows(resultDTOList);

        ResultVO<RowsDataVO<ReservationRoomTypeQueryResultDTO>> resultVO = ResultVO.success();
        resultVO.setData(dataVO);

        return resultVO;
    }

    /**
     * PMS查询房型列表
     *
     * @param params
     * @return
     */
    public ResultVO<RowsDataVO<PMSRoomTypeQueryResultDTO>> getPMSRoomType(PMSRoomTypeQueryDTO params) {
        //获取档登录用户的酒店id
        RoomTypeQueryDTO queryDTO = new RoomTypeQueryDTO();
        BeanUtils.copyProperties(params, queryDTO);
        queryDTO.setJiudianId(manageUserCache.getJiudianId());

        Page page = PageHelper.startPage(params.getPageNo(), params.getPageSize());
        List<YwFangjianleixing> ywjiudianList = queryRoomTypeList(queryDTO);
        //组装返回参数
        List<PMSRoomTypeQueryResultDTO> pmsRoomTypeQueryResultDTOS = ywjiudianList.stream().map(m -> {
                    PMSRoomTypeQueryResultDTO roomTypeQueryResultDTO = new PMSRoomTypeQueryResultDTO();
                    BeanUtils.copyProperties(m, roomTypeQueryResultDTO);
                    roomTypeQueryResultDTO.setZhuangtaiMingcheng(dictInfoCacheExtractor.getDictValue(SysDicConstant.FANGXINGZHUANGTAI, m.getZhuangtai()));
                    roomTypeQueryResultDTO.setTypeMingcheng(dictInfoCacheExtractor.getDictValue(SysDicConstant.FANGXINGMINGCHENG, m.getType()));
                    return roomTypeQueryResultDTO;
                }
        ).collect(Collectors.toList());

        RowsDataVO<PMSRoomTypeQueryResultDTO> dataVO = new RowsDataVO();
        dataVO.setPageNo(page.getPageNum());
        dataVO.setTotalRecords(page.getTotal());
        dataVO.setTotalPages(page.getPages());
        dataVO.setRows(pmsRoomTypeQueryResultDTOS);

        ResultVO<RowsDataVO<PMSRoomTypeQueryResultDTO>> resultVO = ResultVO.success();
        resultVO.setData(dataVO);
        return resultVO;
    }

    /**
     * 查询预订房间类型集合
     *
     * @param bookingRoomTypeQueryDTO
     * @return
     */
    public RowsDataVO<BookingRoomTypeQueryResultDTO> getBookingRoomTypeList(BookingRoomTypeQueryDTO bookingRoomTypeQueryDTO) {
        RowsDataVO<BookingRoomTypeQueryResultDTO> rowsDataVO = new RowsDataVO<>();
        List<BookingRoomTypeQueryResultDTO> bookingRoomTypeQueryResultDTOList = new ArrayList<>();

        QueryConditions conditions = new QueryConditions();
        conditions.addCondition("shanchubiaoshi", EConditionOperator.EQULS, SysDicConstant.DELFLAG_0);
        conditions.addCondition("jiudianId", EConditionOperator.EQULS, manageUserCache.getJiudianId());
        conditions.addCondition("type", EConditionOperator.EQULS, bookingRoomTypeQueryDTO.getType());
        conditions.addCondition("fangxingjiancheng", EConditionOperator.LIKE, bookingRoomTypeQueryDTO.getFangxingjiancheng());
        //获取所有的房型
        MyExample example = new MyExample(YwFangjianleixing.class, conditions, bookingRoomTypeQueryDTO.getOrderFields());
        List<YwFangjianleixing> fangjianleixingList = ywFangjianleixingMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(fangjianleixingList)) {
            return rowsDataVO;
        }

        //循环房型，处理空房
        for (YwFangjianleixing fangjianleixing : fangjianleixingList) {
            RoomUnusedQueryDTO roomUnusedQueryDTO = new RoomUnusedQueryDTO();
            roomUnusedQueryDTO.setKaishishijian(bookingRoomTypeQueryDTO.getKaishishijian());
            roomUnusedQueryDTO.setJieshushijian(bookingRoomTypeQueryDTO.getJieshushijian());
            roomUnusedQueryDTO.setFangxingId(fangjianleixing.getId());
            RowsDataVO<RoomUnusedQueryResultDTO> roomRowsDataVO = roomService.getRoomUnusedList(roomUnusedQueryDTO);
            List<RoomUnusedQueryResultDTO> roomUnusedQueryResultDTOList = roomRowsDataVO.getRows();
            BookingRoomTypeQueryResultDTO teamRoomTypeQueryResultDTO = new BookingRoomTypeQueryResultDTO();
            BeanUtils.copyProperties(fangjianleixing, teamRoomTypeQueryResultDTO);
            if (!CollectionUtils.isEmpty(roomUnusedQueryResultDTOList)) {
                teamRoomTypeQueryResultDTO.setKedingshu(roomUnusedQueryResultDTOList.size());
            } else {
                teamRoomTypeQueryResultDTO.setKedingshu(0);
            }
            bookingRoomTypeQueryResultDTOList.add(teamRoomTypeQueryResultDTO);
        }

        rowsDataVO.setRows(bookingRoomTypeQueryResultDTOList);

        return rowsDataVO;
    }

    /**
     * 查询数据库
     *
     * @param params
     * @return
     */
    private List<YwFangjianleixing> queryRoomTypeList(@Valid RoomTypeQueryDTO params) {
        QueryConditions conditions = new QueryConditions();
        conditions.addCondition("shanchubiaoshi", EConditionOperator.EQULS, SysDicConstant.DELFLAG_0);
        conditions.addCondition("jiudianId", EConditionOperator.EQULS, params.getJiudianId());
        conditions.addCondition("type", EConditionOperator.EQULS, params.getType());
        conditions.addCondition("fangxingjiancheng", EConditionOperator.LIKE, params.getFangxingjiancheng());

        MyExample example = new MyExample(YwFangjianleixing.class, conditions, params.getOrderFields());
        return ywFangjianleixingMapper.selectByExample(example);

    }

    public RoomTypeDetailQueryResultDTO getDetail(RoomTypeDetailQueryDTO roomDetailQueryDTO) {
        RoomTypeDetailQueryResultDTO resultDTO = new RoomTypeDetailQueryResultDTO();
        YwFangjianleixing ywFangjianleixing = ywFangjianleixingMapper.selectByPrimaryKey(roomDetailQueryDTO.getId());

        if (null == ywFangjianleixing) {
            return null;
        }
        BeanUtils.copyProperties(ywFangjianleixing, resultDTO);
        resultDTO.setZaocanleixingMingcheng(dictInfoCacheExtractor.getDictValue(SysDicConstant.ZAOCANLEIXING, resultDTO.getZaocanleixing()));
        resultDTO.setTypeName(dictInfoCacheExtractor.getDictValue(SysDicConstant.FANGJIANLEIXING, resultDTO.getType()));
        resultDTO.setShangwangfangshiMingcheng(dictInfoCacheExtractor.getDictValue(SysDicConstant.SHANGWANGFANGSHI, resultDTO.getShangwangfangshi()));

        return resultDTO;

    }

    @Transactional
    public ResultVO add(RoomTypeAddDTO addQueryResultDTO) {
        ResultVO resultVO = ResultVO.success();

        if (resultVO.getCode() == ResultVO.FAIL) {
            return resultVO;
        }

        LoginManageResultVO user = manageUserCache.getLoginManageUserInfo();

        YwFangjianleixing ywFangjianleixing = new YwFangjianleixing();
        BeanUtils.copyProperties(addQueryResultDTO, ywFangjianleixing);
        // TODO: 2019/7/2 房型编号待加
        ywFangjianleixing.setFangxingbianhao("FX" + RandomUtil.getRandomByRange(1, 1000));
        ywFangjianleixing.setJiudianId(user.getJiudianId());
        ywFangjianleixing.setChuangjianshijian(new Date());
        ywFangjianleixing.setChuangjianrenId(user.getId());
        ywFangjianleixing.setGengxinrenId(user.getId());
        ywFangjianleixing.setGengxinshijian(new Date());
        ywFangjianleixing.setZhuangtai(SysDicConstant.ZHUANGTAI_YOU_XIAO);
        ywFangjianleixing.setShanchubiaoshi(SysDicConstant.DELFLAG_0);
        int insert = ywFangjianleixingMapper.insert(ywFangjianleixing);
        if (insert == 0) {
            resultVO = ResultVO.fail();
        }
        return resultVO;
    }

    @Transactional
    public ResultVO del(RoomTypeDelResultDTO hotelInfoModifyDTO) {
        ResultVO resultVO = ResultVO.success();

        if (resultVO.getCode() == ResultVO.FAIL) {
            return resultVO;
        }
        YwFangjianleixing ywFangjianleixing = new YwFangjianleixing();
        BeanUtils.copyProperties(hotelInfoModifyDTO, ywFangjianleixing);
        ywFangjianleixing.setGengxinshijian(new Date());
        ywFangjianleixing.setGengxinrenId(manageUserCache.getCurrentUserId());
        ywFangjianleixing.setShanchubiaoshi(SysDicConstant.DELFLAG_1);
        int insert = ywFangjianleixingMapper.updateByPrimaryKeySelective(ywFangjianleixing);
        if (insert == 0) {
            resultVO = ResultVO.fail();
        }
        return resultVO;
    }

    public ResultVO stop(RoomTypeStopDTO params) {
        ResultVO resultVO = ResultVO.success();

        if (resultVO.getCode() == ResultVO.FAIL) {
            return resultVO;
        }
        YwFangjianleixing ywFangjianleixing = new YwFangjianleixing();
        BeanUtils.copyProperties(params, ywFangjianleixing);
        ywFangjianleixing.setGengxinshijian(new Date());
        ywFangjianleixing.setGengxinrenId(manageUserCache.getCurrentUserId());
        ywFangjianleixing.setZhuangtai(SysDicConstant.ZHUANGTAI_WU_XIOA);
        int count = ywFangjianleixingMapper.updateByPrimaryKeySelective(ywFangjianleixing);
        if (count == 0) {
            return ResultVO.fail();
        }
        return resultVO;
    }

    @Transactional
    public ResultVO modify(@Valid RoomTypeModifyDTO roomModifyQueryDTO) {

        ResultVO resultVO = ResultVO.success();

        if (resultVO.getCode() == ResultVO.FAIL) {
            return resultVO;
        }
        YwFangjianleixing ywFangjianleixing = new YwFangjianleixing();
        BeanUtils.copyProperties(roomModifyQueryDTO, ywFangjianleixing);
        ywFangjianleixing.setGengxinrenId(manageUserCache.getCurrentUserId());
        ywFangjianleixing.setGengxinshijian(new Date());
        int count = ywFangjianleixingMapper.updateByPrimaryKeySelective(ywFangjianleixing);
        if (count == 0) {
            resultVO = ResultVO.fail();
        }

        return resultVO;
    }

}
